package com.haitaoit.chengquan.ui.equipment.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.IBaseActivity;
import com.haitaoit.chengquan.base.MyCallBack;
import com.haitaoit.chengquan.module.center.model.ProvinceBase;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.center.model.area;
import com.haitaoit.chengquan.module.home.adapter.forum.ImageAdapter;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.bean.SBWXAddRequirementBean;
import com.haitaoit.chengquan.ui.equipment.request.ApiRequest;
import com.haitaoit.chengquan.ui.equipment.response.ResponseItem;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetPhotoListener;
import com.haitaoit.chengquan.utils.GetPhotoOrImage;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PhonUnmber;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.pickerview.TimePopupWindow;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 赵航 on 2017/10/17.
 */

public class JCSendNeedActivity extends IBaseActivity {
    @ViewInject(R.id.tv_jgdd_release)
    TextView tv_jgdd_release;//发布
    @ViewInject(R.id.tv_jgdd_type)
    TextView tv_jgdd_type;//需求分类
    @ViewInject(R.id.et_jgdd_title)
    EditText et_jgdd_title;//需求标题
     @ViewInject(R.id.jcsendneedactivity_material)
    EditText jcsendneedactivity_material;//机床型号
     @ViewInject(R.id.hcsendneedactivity_material)
    EditText hcsendneedactivity_material;//机床系统型号
     @ViewInject(R.id.jcsendneedactivity_pepelo_material)
    EditText jcsendneedactivity_pepelo_material;//人数
    @ViewInject(R.id.et_jgdd_describe)
    EditText et_jgdd_describe;//详细描述
    @ViewInject(R.id.et_jgdd_num)
    EditText et_jgdd_num;//组立项目
    @ViewInject(R.id.et_jgdd_material)
    EditText et_jgdd_material;//组立数量
    @ViewInject(R.id.tv_end_time)
    TextView tv_end_time;//报价截止时间
    @ViewInject(R.id.et_jgdd_price)
    EditText et_jgdd_price;//参考价格
    @ViewInject(R.id.jcsendneedactivity_s_material)
    EditText   jcsendneedactivity_s_material;//规格型号
     @ViewInject(R.id.hcsendneedactivity_leixing)
    EditText   hcsendneedactivity_leixing;//组立品牌
    @ViewInject(R.id.et_jgdd_address)
    EditText   et_jgdd_address;//需求地点
    @ViewInject(R.id.et_jgdd_peopel)
    EditText   et_jgdd_peopel;//联系人
    @ViewInject(R.id.et_jgdd_company)
    EditText   et_jgdd_company;//公司名称
    @ViewInject(R.id.et_jgdd_position)
    EditText   et_jgdd_position;//联系人职位
    @ViewInject(R.id.et_jgdd_phone)
    EditText   et_jgdd_phone;//联系人电话
    @ViewInject(R.id.img_list)
    MyGridView img_list;
    @ViewInject(R.id.iv_jgdd_title)
    ImageView  iv_jgdd_title;
    // 上传的bitmap
    private Bitmap upbitmap;
    private String file = "";
    private ImageAdapter    adapter;
    private GetPhotoOrImage getPhotoOrImage;
    private int change = 0;



    private List<ProvinceBase>                                    province;
    private List<com.haitaoit.chengquan.module.center.model.city> city;
    private List<area>                                            region;

    private ArrayList<String> options1Items = new ArrayList<String>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<ArrayList<String>>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<ArrayList<ArrayList<String>>>();

    private double latitude = 0;// 维度
    private double longitude = 0;// 经度
    private GeoCoder mSearch;
    private String mAccount_type;
    @Override
    protected int setContentView() {
        return R.layout.activity_jcsendneedactivity_add_requirement;
    }
    @Override
    protected String setTitle() {
        if (TextUtils.equals(mAccount_type, "2") || TextUtils.equals(mAccount_type, "3")) {
            return "机床组立 发布服务";
        }
        return "机床组立 发布需求";
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAccount_type = PreferenceUtils.getPrefString("account_type", "");
    }

    @Override
    protected void initView() {
        mAccount_type = PreferenceUtils.getPrefString("account_type", "");
        adapter = new ImageAdapter(this);
        adapter.setBackCall(backCall);
        img_list.setAdapter(adapter);
        getPhotoOrImage = new GetPhotoOrImage(this);


        tv_jgdd_type.setText("机床组立");
        tv_jgdd_release.setOnClickListener(this);
        iv_jgdd_title.setOnClickListener(this);
        tv_end_time.setOnClickListener(this);
        httpGetUserInfo();
    }
    private void httpGetUserInfo() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.GetUser_model, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            et_jgdd_peopel.setText(user_info.getNet_name());
                            et_jgdd_phone.setText(user_info.getPhone());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }
    @Override
    protected void initData() {

    }
    @Override
    protected void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.tv_end_time://选择截止时间
                TimePopupWindow startTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
                startTime.setTime(new Date());// 时间选择后回调
                startTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        try {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date d1 = dateFormat.parse(getTime(date));
                            Date d2 = dateFormat.parse(dateFormat.format(new Date()));
                            if (d1.getTime() < d2.getTime()) {
                                ToastUtils.showToast("截止时间要大于当前时间!");
                            } else {
                                tv_end_time.setText(getTime(date));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                startTime.showAtLocation(tv_end_time, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.iv_jgdd_title://选择title图片
                Dialog dlg = DialogUtil.ShowPhotoDialog(this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 500);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.tv_jgdd_release://发布
                tv_jgdd_release.setEnabled(false);
                if (mAccount_type.equals("")) {
                    tv_jgdd_release.setEnabled(true);
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                } else if (mAccount_type.equals("1")) {
                    if (TextUtils.isEmpty(getSStr(et_jgdd_title))) {
                        ToastUtils.showToast("请输入需求标题！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_describe))) {
                        ToastUtils.showToast("请输入详细描述！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_num))) {
                        ToastUtils.showToast("请输入组立项目！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_material))) {
                        ToastUtils.showToast("输入组立数量！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(hcsendneedactivity_leixing))) {
                        ToastUtils.showToast("请输入组立品牌！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(jcsendneedactivity_s_material))) {
                        ToastUtils.showToast("输入机床组立规格型号！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(jcsendneedactivity_material))) {
                        ToastUtils.showToast("输入机床型号！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    }else if (TextUtils.isEmpty(getSStr(jcsendneedactivity_pepelo_material))) {
                        ToastUtils.showToast("输入人数！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(tv_end_time))) {
                        ToastUtils.showToast("请选择截止时间");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_price))) {
                        ToastUtils.showToast("请输入参考价格！");
                        return;

                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_address))) {
                        tv_jgdd_release.setEnabled(true);
                        ToastUtils.showToast("请输入需求地点！");
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_peopel))) {
                        ToastUtils.showToast("请输入联系人！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(getSStr(et_jgdd_company))) {
                        ToastUtils.showToast("请输入公司名称！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    }  else if (TextUtils.isEmpty(getSStr(et_jgdd_phone))) {
                        ToastUtils.showToast("请输入联系人电话！");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    } else if (PhonUnmber.checkCellphone(et_jgdd_phone.getText().toString().trim())) {
                        ToastUtils.showToast("联系人电话不正确");
                        tv_jgdd_release.setEnabled(true);
                        return;
                    }else {
                        // 获取经纬度
                        if (hasNetWork()) {
                            mSearch = GeoCoder.newInstance();
                            mSearch.geocode(new GeoCodeOption().city("").address(et_jgdd_address.getText().toString()));
                            mSearch.setOnGetGeoCodeResultListener(listener);
                        }else {
                            tv_jgdd_release.setEnabled(true);
                        }
                    }

                } else {
                    tv_jgdd_release.setEnabled(true);
                    ToastUtils.showToast(getString(R.string.qSendNeed_service_can_puservice));
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2) {
            if (data != null) {
                upbitmap = null;
                if (data.getExtras() != null && !("").equals(data.getExtras())) {
                    upbitmap = (Bitmap) data.getExtras().get("data");
                } else {
                    String str = data.getDataString();
                    if (str == null) {
                        return;
                    }
                    Uri uri = Uri.parse(str);
                    String path = GetAbserlutePath.getPath(this, uri);
                    if (path.endsWith("png") || path.endsWith("jpg") || path.endsWith("jpeg")) {// 图片
                        upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                    } else {
                        ToastUtils.showToast("请选择.jpg或.png或.jpeg格式的图片!");
                        return;
                    }
                }
                upbitmap = getSmallBitmap(upbitmap);
                file = bitmapToString(upbitmap);
                iv_jgdd_title.setImageBitmap(upbitmap);
            }
        } else {
            getPhotoOrImage.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    private void httpadd_demand() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        SBWXAddRequirementBean sbwxBean = new SBWXAddRequirementBean();
        sbwxBean.setType(3);//1设备维修2机床耗材3机床组立4机床配件5加工订单6二手货设备买卖7二手货设置改造
        //需求标题
        sbwxBean.setTitle(et_jgdd_title.getText().toString());
        //详细描述
        sbwxBean.setDescribe(et_jgdd_describe.getText().toString());




        //组立项目
        sbwxBean.setJczl_group_project(et_jgdd_num.getText().toString());
        //组立数量
        sbwxBean.setJczl_group_number(et_jgdd_material.getText().toString());
        //组立品牌
        sbwxBean.setJczl_group_brand(hcsendneedactivity_leixing.getText().toString());
        //机床组立规格型号
        sbwxBean.setJczl_specifications(jcsendneedactivity_s_material.getText().toString());
        //机床型号
        sbwxBean.setJczl_machine(jcsendneedactivity_material.getText().toString());
        //系统型号
        sbwxBean.setJczl_system(hcsendneedactivity_material.getText().toString());
        //人数
        sbwxBean.setJczl_numbe(jcsendneedactivity_pepelo_material.getText().toString());




        //报名截止时间
        sbwxBean.setOffer_end_time(tv_end_time.getText().toString());
        //参考价格
        sbwxBean.setReference_price(Double.parseDouble(et_jgdd_price.getText().toString()));
        //需求地点
        sbwxBean.setDemand_site(et_jgdd_address.getText().toString());
        //联系人
        sbwxBean.setContact(et_jgdd_peopel.getText().toString());
        //公司名称
        sbwxBean.setCompany_name(et_jgdd_company.getText().toString());
        //联系人人职位
//        sbwxBean.setContact_position(getSStr(et_jgdd_position));
        //联系人电话
        sbwxBean.setContact_phone(getSStr(et_jgdd_phone));
        //经纬度
        sbwxBean.setLatitude(latitude);
        sbwxBean.setLongitude(longitude);

        //标题图片
        SBWXAddRequirementBean.TitleImgBean titleImgBean = new SBWXAddRequirementBean.TitleImgBean();
        if (file == null || "".equals(file)) {
            file = bitmapToString(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.img20));
        }

        titleImgBean.setImg_url(file);
        sbwxBean.setTitle_img(titleImgBean);
        //轮播图片
        List<SBWXAddRequirementBean.ImgListBean> imgList = new ArrayList<SBWXAddRequirementBean.ImgListBean>();
        SBWXAddRequirementBean.ImgListBean imgBean;
        for (int i = 0; i < adapter.getList().size(); i++) {
            imgBean = new SBWXAddRequirementBean.ImgListBean();
            imgBean.setImg_url(adapter.getList().get(i).getImg());
            imgList.add(imgBean);
        }
        sbwxBean.setImg_list(imgList);

        if (hasNetWork()) {
            ApiRequest.SBWXAddRequirement(PreferenceUtils.getPrefString("user_id", ""), sign, sbwxBean, new MyCallBack<ResponseItem>(mContext) {
                @Override
                public void onSuccessful(ResponseItem response) {
                    tv_jgdd_release.setEnabled(true);
                    if (response.getErrCode() == 0) {
                        setResult(1);
                        finish();
                        return;
                    }
                    tv_jgdd_release.setEnabled(true);
                    ToastUtils.showToast(response.getErrMsg());
                }
                @Override
                protected void onError(Throwable throwable) {
                    super.onError(throwable);
                    tv_jgdd_release.setEnabled(true);
                    ToastUtils.showToast("发布失败,请稍后重试");
                }
            });
        }else {
            tv_jgdd_release.setEnabled(true);
        }
    }


    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {//获取地址
                // 没有检索到结果
                ToastUtils.showToast("亲,您的地址是无效的,请重新填写哦!");
                tv_jgdd_release.setEnabled(true);
            } else {// 获取地理编码结果
                Log.e("tag", "result1:" + result.getAddress() + "====" + result.getLocation().latitude + "-----" + result.getLocation().longitude);
                latitude = result.getLocation().latitude;
                longitude = result.getLocation().longitude;
                // 发布
                httpadd_demand();
            }
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {// 获取经纬度
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            } else {// 获取反向地理编码结果
                Log.e("tag", "reverseGeoCodeResult1:" + reverseGeoCodeResult.toString());
            }
        }
    };

    private void province(InputStream inputStream) {
        String a = getString(inputStream);
        try {
            JSONObject jsondata = new JSONObject(a);
            Gson gson = new Gson();
            province = gson.fromJson(jsondata.getString("data"),
                    new TypeToken<List<ProvinceBase>>() {
                    }.getType());
            //            Log.e("tag", province.toString());
            ArrayList<String> options2Items_i = null;
            ArrayList<ArrayList<String>> options3Items_j = null;
            for (int i = 0; i < province.size(); i++) {
                options1Items.add(province.get(i).getName());
                city = province.get(i).getCity();
                options2Items_i = new ArrayList<String>();
                options3Items_j = new ArrayList<ArrayList<String>>();
                for (int j = 0; j < city.size(); j++) {
                    options2Items_i.add(city.get(j).getName());
                    region = city.get(j).getArea();
                    ArrayList<String> options3Items_j_j2 = new ArrayList<String>();
                    for (int j2 = 0; j2 < region.size(); j2++) {
                        options3Items_j_j2.add(region.get(j2).getName());
                    }
                    options3Items_j.add(options3Items_j_j2);
                }
                options2Items.add(options2Items_i);
                options3Items.add(options3Items_j);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.set(change, img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 处理调用相机或者相册的图片回调
    GetPhotoListener getPhoto1 = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.add(img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    /**
     * 日期格式
     *
     * @param date
     * @return
     */
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.icon:
                    if (position == adapter.getList().size()) {
                        getPhotoOrImage.setGetPhotoListener(getPhoto1);
                        getPhotoOrImage.getImage();
                    } else {
                        Dialog dlg = DialogUtil.ShowTop(mContext, new BackCall() {
                            @Override
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.tv_photos:// 图库
                                        getPhotoOrImage.setGetPhotoListener(getPhoto);
                                        getPhotoOrImage.getImage();
                                        break;
                                    case R.id.tv_camera:
                                        List<Img> list = adapter.getList();
                                        list.remove(change);
                                        adapter.setList(list);
                                        adapter.notifyDataSetChanged();
                                        break;
                                }
                                super.deal(which, obj);
                            }
                        });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        mContext.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

}
